<?php
defined('SYSPATH') OR die('No direct access allowed.');
/**
 * user.php
 * @author ranuandra
 *
 * 15 Mei 2012 12:58:34
 *
 * 
 */

class Controller_Admin_User extends Kohana_Admin
{
	
	public function action_index()
	{
		$users = ORM::factory('user')->where('mstplacement_id', '!=', NULL)->find_all();
		$view = View::factory('admin/user/index');
		$view->datas = $users;
		
		$this->template->container = $view;
		
	}
	public function action_bydepartment()
	{
		$this->auto_render = false;
		$id = Request::current()->param('id');
		$users = ORM::factory('user')->where('mstplacement_id', '=', $id)->find_all()->as_array('id', 'username');
		$view = View::factory('admin/user/list');
		$view->users = $users;
		
		echo $view;
		
		//$this->template->container = $view;		
	}	
	public function action_new()
	{
		$form = array(
				'username'			=> '',
				'password'			=> '',
				'password_confirm'	=> '',
				'email'				=> '',
		);
		
		$view = View::factory('admin/user/form');
		$view->form = $form;
		$view->placements = ORM::factory('mstplacement')->find_all()->as_array('id', 'placement');
		$this->template->container = $view;
	}
	
	public function action_edit()
	{
		$id = Request::current()->param('id');
		$form = ORM::factory('user')->where('id', '=', $id)->find()->as_array();
		
		$view = View::factory('admin/user/form');
		$view->form = $form;
		$this->template->container = $view;
	}
	
	public function action_save()
	{
		if(isset($_POST['submit']))
		{
			$db = Database::instance();
			$db->begin();
			
			print_r($_POST);
			
			try 
			{
				if(isset($_POST['id']))
				{
					$user = ORM::factory('user', Request::current()->post('id'));
					
					$user->username = Request::current()->post('username');
					$user->email = Request::current()->post('email');
					$user->mstplacement_id = Request::current()->post['mstplacement_id'];
					if(Request::current()->post('password') != "" && Request::current()->post('password_confirm') != "" )
					{
						$user->password = Request::current()->post('password');
						$user->confirm_password = Request::current()->post('password_confirm');
					}					
					$user->save();
				}
				else 
				{
					$user = ORM::factory('user');
					$user->mstplacement_id = $_POST['mstplacement_id'];
					$user->create_user($_POST, array(
					 										'username',
															'password',
					 										'email',
					  									));
			  		$login_role = new Model_Role(array('name' =>'login'));
					$user->add('roles',$login_role);
			  		$login_role = new Model_Role(array('name' =>'cabang'));
					$user->add('roles',$login_role);
				}
				
				$db->commit();
				Request::current()->redirect(URL::base().'admin/user');
				exit;
			}
			catch(ORM_Validation_Exception $e)
			{
				$db->rollback();
				$errors = $e->errors('models');
				print_r($errors);
			}
		}				
	}
	
}